Skip to content

Lemon Squeezy Importer - #4214

Open
pepeladeira wants to merge 20 commits into
mainfrom
lemonsqueezy-importer
Open

Lemon Squeezy Importer#4214
pepeladeira wants to merge 20 commits into
mainfrom
lemonsqueezy-importer

Conversation

@pepeladeira

@pepeladeira pepeladeira commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added Lemon Squeezy as a program import source.
    • Import partners, customers, orders, subscriptions, and commission data from a selected store.
    • Added a guided setup flow for entering an API key, selecting a store, and starting imports.
    • Added progress handling, validation, duplicate prevention, and import error reporting.
    • Added support for Lemon Squeezy sales and import notifications.
  • Bug Fixes

    • Improved customer identification across payment-related events using consistent metadata handling.

@vercel

vercel Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
dub Ready Ready Preview Aug 10, 2026 12:49pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7703e444-75d7-42c7-bfe5-17d2c96012cc

📥 Commits

Reviewing files that changed from the base of the PR and between 0cc97ac and c444b3f.

📒 Files selected for processing (8)
  • apps/web/lib/actions/partners/set-lemonsqueezy-token.ts
  • apps/web/lib/actions/partners/start-lemonsqueezy-import.ts
  • apps/web/lib/lemonsqueezy/client.ts
  • apps/web/lib/lemonsqueezy/import-commissions.ts
  • apps/web/lib/lemonsqueezy/import-customers.ts
  • apps/web/lib/lemonsqueezy/import-partners.ts
  • apps/web/lib/lemonsqueezy/schemas.ts
  • apps/web/lib/lemonsqueezy/types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/web/lib/actions/partners/set-lemonsqueezy-token.ts
  • apps/web/lib/actions/partners/start-lemonsqueezy-import.ts
  • apps/web/lib/lemonsqueezy/types.ts
  • apps/web/lib/lemonsqueezy/import-partners.ts
  • apps/web/lib/lemonsqueezy/import-commissions.ts
  • apps/web/lib/lemonsqueezy/import-customers.ts

📝 Walkthrough

Walkthrough

The PR adds Lemon Squeezy API contracts, credential setup, staged partner/customer/commission imports, cron dispatch, and modal integration. It also centralizes Stripe customer external ID extraction across checkout, invoice, and synchronization webhooks.

Changes

Lemon Squeezy import

Layer / File(s) Summary
Provider contracts and API client
apps/web/lib/lemonsqueezy/..., apps/web/lib/constants/program.ts, apps/web/lib/zod/schemas/..., packages/email/src/templates/program-imported.tsx
Adds validated Lemon Squeezy schemas, inferred types, JSON:API pagination, resource flattening, API listing methods, program configuration, accepted source values, and email provider support.
Credential onboarding and import queueing
apps/web/lib/actions/partners/..., apps/web/lib/lemonsqueezy/importer.ts, apps/web/ui/modals/..., apps/web/app/app.dub.co/.../partners-menu-popover.tsx
Validates API keys, stores workspace credentials, verifies store ownership, queues imports, and exposes the two-step import modal through the modal provider and partners menu.
Partner and customer import stages
apps/web/lib/lemonsqueezy/import-partners.ts, apps/web/lib/lemonsqueezy/import-customers.ts
Imports affiliates, enrollments, links, and referred customers with pagination, duplicate handling, import-error logging, click and lead recording, statistics updates, and continuation jobs.
Commission import and cron dispatch
apps/web/lib/lemonsqueezy/import-commissions.ts, apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts
Dispatches import actions and processes orders and subscription invoices into validated, deduplicated commissions, sale events, statistics, completion email, and credential cleanup.

Stripe metadata resolution

Layer / File(s) Summary
Centralized Stripe customer ID extraction
apps/web/app/(ee)/api/stripe/integration/webhook/...
Adds shared metadata fallback precedence and uses it in checkout completion, invoice-paid, and customer synchronization flows.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ImportModal
  participant ServerActions
  participant LemonSqueezyAPI
  participant QStash
  participant CronRoute
  participant ImportStages
  ImportModal->>ServerActions: submit API key and store
  ServerActions->>LemonSqueezyAPI: validate key and store ownership
  ServerActions->>QStash: queue partner import
  QStash->>CronRoute: invoke import action
  CronRoute->>ImportStages: run partner, customer, or commission stage
  ImportStages->>QStash: queue continuation stage
Loading

Possibly related PRs

  • dubinc/dub#2600: Introduces the importer architecture and workflow patterns reused by the Lemon Squeezy integration.
  • dubinc/dub#4158: Shares the Stripe customer synchronization utility used by this PR.
  • dubinc/dub#4170: Introduces the withCron pattern used by the Lemon Squeezy cron endpoint.

Suggested reviewers: devkiran, steven-tey

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding a Lemon Squeezy importer.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch lemonsqueezy-importer

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pepeladeira
pepeladeira marked this pull request as ready for review August 3, 2026 22:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/ui/modals/modal-provider.tsx (1)

50-64: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep one owner for ImportLemonSqueezyModal.

PartnersMenuPopover also mounts ImportLemonSqueezyModal. Both instances observe ?import=lemonsqueezy, so one import selection opens two dialogs and renders duplicate form controls. Remove this provider integration to match the existing partner-import pattern, or remove the menu integration and make the provider the only owner.

Also applies to: 120-121, 208-223

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/ui/modals/modal-provider.tsx` around lines 50 - 64, Ensure
ImportLemonSqueezyModal has a single owner by removing its modal-provider
integration: delete the setShowImportLemonSqueezyModal context state, default,
provider wiring, and related render block around the provider symbols, while
preserving the PartnersMenuPopover-owned modal and existing import behavior.
🧹 Nitpick comments (1)
apps/web/lib/lemonsqueezy/import-commissions.ts (1)

76-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

toDubStatus never returns null.

The default branch returns "pending", so the | null return type and the if (!status) return; guard at lines 407-410 are unreachable. Either drop null from the signature and remove the guard, or return null for unknown statuses if you want to skip them.

♻️ Proposed change
-const toDubStatus = (status: string): CommissionStatus | null => {
+const toDubStatus = (status: string): CommissionStatus => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/lib/lemonsqueezy/import-commissions.ts` around lines 76 - 93, Update
toDubStatus so its return type and behavior agree: either remove null from the
return type and delete the unreachable !status guard in the caller, or return
null for unknown statuses so that guard can skip them. Preserve the existing
mappings for recognized statuses.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 566-609: Update the import flow around the per-page sale-event
processing and the sale handling shown here to group events by
customerExternalId, process each customer’s events sequentially in createdAt
order, and mark only the earliest event as eligible for first-conversion and
firstSaleAt updates. Ensure later events for the same customer do not reuse
stale customer state to increment link conversions or overwrite firstSaleAt,
while preserving normal sale and amount increments for every event.

In `@apps/web/lib/lemonsqueezy/import-customers.ts`:
- Around line 119-141: Update the customer processing loop in importCustomers to
use Promise.allSettled instead of Promise.all, preserving processing of all
chunks and allowing the importer queue to run when an individual createCustomer
call fails. Also update the recordClick result handling so its nullable return
is guarded before constructing the clickEventSchemaTB payload, including the
required bot and qr fields only when a valid result exists.
- Around line 74-80: Scope both affiliate-by-domain link lookups to the current
program by adding program.id to the where filters in
apps/web/lib/lemonsqueezy/import-customers.ts lines 74-80 and
apps/web/lib/lemonsqueezy/import-commissions.ts lines 333-340. Update the
findMany calls in both import flows so matching requires the domain, affiliate
key, and programId.

In `@apps/web/lib/lemonsqueezy/import-partners.ts`:
- Around line 221-226: Update the duplicate-link log in the partner import flow
to stop including partner.email, and report the partner’s id instead while
preserving the existing affiliate key and skip behavior.
- Around line 101-114: Inspect the results returned by Promise.allSettled in the
activeAffiliates import flow and log each rejected createPartnerAndLinks
operation with its rejection reason. Preserve successful imports and ensure
failures from any stage, including database upserts, produce an import-error log
identifying the affected affiliate.

In `@apps/web/lib/lemonsqueezy/importer.ts`:
- Around line 13-37: Update setCredentials, getCredentials, and
deleteCredentials to scope cached Lemon Squeezy credentials to each import
rather than only the workspace. Add or propagate importId through these methods
and include it in the Redis key, preserving the existing expiry,
missing-credential error, and deletion behavior so concurrent imports do not
overwrite or remove one another’s credentials.

In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 140-143: Update the stores-loading flow around setStores and
setStep("select-store") to verify data.stores contains at least one store before
advancing. Keep the token form open for an empty array, and display the existing
error UI/message for API keys with no accessible stores.

---

Outside diff comments:
In `@apps/web/ui/modals/modal-provider.tsx`:
- Around line 50-64: Ensure ImportLemonSqueezyModal has a single owner by
removing its modal-provider integration: delete the
setShowImportLemonSqueezyModal context state, default, provider wiring, and
related render block around the provider symbols, while preserving the
PartnersMenuPopover-owned modal and existing import behavior.

---

Nitpick comments:
In `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 76-93: Update toDubStatus so its return type and behavior agree:
either remove null from the return type and delete the unreachable !status guard
in the caller, or return null for unknown statuses so that guard can skip them.
Preserve the existing mappings for recognized statuses.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c243eba-cba5-4793-88a6-0116d385786b

📥 Commits

Reviewing files that changed from the base of the PR and between 5b5c7e5 and 9748846.

📒 Files selected for processing (21)
  • apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-dub-customer-external-id-from-metadata.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
  • apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-menu-popover.tsx
  • apps/web/lib/actions/partners/set-lemonsqueezy-token.ts
  • apps/web/lib/actions/partners/start-lemonsqueezy-import.ts
  • apps/web/lib/constants/program.ts
  • apps/web/lib/lemonsqueezy/api.ts
  • apps/web/lib/lemonsqueezy/import-commissions.ts
  • apps/web/lib/lemonsqueezy/import-customers.ts
  • apps/web/lib/lemonsqueezy/import-partners.ts
  • apps/web/lib/lemonsqueezy/importer.ts
  • apps/web/lib/lemonsqueezy/schemas.ts
  • apps/web/lib/lemonsqueezy/types.ts
  • apps/web/lib/zod/schemas/import-error-log.ts
  • apps/web/lib/zod/schemas/sales.ts
  • apps/web/ui/modals/import-lemonsqueezy-modal.tsx
  • apps/web/ui/modals/modal-provider.tsx
  • packages/email/src/templates/program-imported.tsx

Comment thread apps/web/lib/lemonsqueezy/import-commissions.ts
Comment thread apps/web/lib/lemonsqueezy/import-customers.ts
Comment thread apps/web/lib/lemonsqueezy/import-customers.ts
Comment thread apps/web/lib/lemonsqueezy/import-partners.ts
Comment thread apps/web/lib/lemonsqueezy/import-partners.ts
Comment thread apps/web/lib/lemonsqueezy/importer.ts
Comment thread apps/web/ui/modals/import-lemonsqueezy-modal.tsx Outdated
@pepeladeira

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review. any breaking changes or security issues?

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

@pepeladeira I will run a full review of PR #4214. I will check breaking changes, authorization, credential handling, input validation, import idempotency, and external API interactions.

✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
apps/web/ui/modals/import-lemonsqueezy-modal.tsx (1)

253-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expose the selection state to assistive technology.

The store list behaves like a radio group, but the markup uses plain buttons. The selected store is communicated only by the visual Check2 icon. Add role="radiogroup" to the container and role="radio" with aria-checked={checked} to each button, so screen readers announce which store is selected.

♻️ Proposed change
-          <div className="flex w-full flex-col gap-1 p-1">
+          <div role="radiogroup" aria-label="Choose a store to import" className="flex w-full flex-col gap-1 p-1">
             {stores.map((store) => {
               const checked = selectedStoreId === store.id;
 
               return (
                 <button
                   key={store.id}
                   type="button"
+                  role="radio"
+                  aria-checked={checked}
                   onClick={() => setSelectedStoreId(store.id)}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx` around lines 253 - 297,
Update the store selection markup in the ScrollContainer to expose its
radio-group semantics: add role="radiogroup" to the list container and
role="radio" with aria-checked={checked} to each store button generated in the
stores.map callback.
apps/web/lib/lemonsqueezy/api.ts (1)

100-116: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider retrying on 429 instead of only reporting Retry-After.

The client reads Retry-After but only embeds it in the error message. A single rate-limited page then throws and aborts the current import batch. Add a bounded retry that waits for Retry-After before failing, so long imports survive normal rate limiting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/lib/lemonsqueezy/api.ts` around lines 100 - 116, Update the non-OK
response handling in the Lemon Squeezy request flow to retry 429 responses a
bounded number of times, waiting for the duration specified by Retry-After
before each retry. After the retry limit is reached, preserve the existing error
construction and reporting behavior; non-429 responses should continue failing
immediately.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/lib/constants/program.ts`:
- Around line 40-45: Update the helpUrl for the lemonsqueezy entry in the
program constants and the corresponding import-modal occurrence to a currently
published, non-404 help article URL; keep both references consistent.

In `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 76-93: Update toDubStatus so its behavior and return type agree:
either return null for unrecognized Lemon Squeezy statuses and retain the
existing null guard while logging skipped commissions, or keep the pending
fallback and change the return type to CommissionStatus while removing the dead
guard at the commission import call site. Choose the intended policy and apply
it consistently.
- Around line 186-214: Move the lemonSqueezyImporter.deleteCredentials call in
the completed import flow to after the workspaceUser lookup and conditional
sendEmail call. Keep credential deletion as the final step so retries can still
retrieve credentials if the lookup or completion email fails.
- Around line 366-380: Update the commission processing loop in
processSaleEvents to use Promise.allSettled instead of Promise.all when invoking
createCommission for each saleChunk, matching the pattern used by
importCustomers. Preserve processing of all sale events, chunks, and subsequent
continuation or subscription-invoices handoffs even when an individual
createCommission call rejects.

In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 147-149: Both action error handlers in
import-lemonsqueezy-modal.tsx can pass undefined to toast.error; update the
handlers at lines 147-149 and 228-230 to fall back from error.serverError to
“Failed to fetch Lemon Squeezy stores.” and “Failed to start the Lemon Squeezy
import.” respectively.

---

Nitpick comments:
In `@apps/web/lib/lemonsqueezy/api.ts`:
- Around line 100-116: Update the non-OK response handling in the Lemon Squeezy
request flow to retry 429 responses a bounded number of times, waiting for the
duration specified by Retry-After before each retry. After the retry limit is
reached, preserve the existing error construction and reporting behavior;
non-429 responses should continue failing immediately.

In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 253-297: Update the store selection markup in the ScrollContainer
to expose its radio-group semantics: add role="radiogroup" to the list container
and role="radio" with aria-checked={checked} to each store button generated in
the stores.map callback.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 49f0143b-31cd-4ce9-a1e2-58a1d46193dd

📥 Commits

Reviewing files that changed from the base of the PR and between 73c5809 and 0f018ce.

📒 Files selected for processing (21)
  • apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-dub-customer-external-id-from-metadata.ts
  • apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
  • apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-menu-popover.tsx
  • apps/web/lib/actions/partners/set-lemonsqueezy-token.ts
  • apps/web/lib/actions/partners/start-lemonsqueezy-import.ts
  • apps/web/lib/constants/program.ts
  • apps/web/lib/lemonsqueezy/api.ts
  • apps/web/lib/lemonsqueezy/import-commissions.ts
  • apps/web/lib/lemonsqueezy/import-customers.ts
  • apps/web/lib/lemonsqueezy/import-partners.ts
  • apps/web/lib/lemonsqueezy/importer.ts
  • apps/web/lib/lemonsqueezy/schemas.ts
  • apps/web/lib/lemonsqueezy/types.ts
  • apps/web/lib/zod/schemas/import-error-log.ts
  • apps/web/lib/zod/schemas/sales.ts
  • apps/web/ui/modals/import-lemonsqueezy-modal.tsx
  • apps/web/ui/modals/modal-provider.tsx
  • packages/email/src/templates/program-imported.tsx

Comment thread apps/web/lib/constants/program.ts
Comment thread apps/web/lib/lemonsqueezy/import-commissions.ts Outdated
Comment thread apps/web/lib/lemonsqueezy/import-commissions.ts Outdated
Comment thread apps/web/lib/lemonsqueezy/import-commissions.ts
Comment thread apps/web/ui/modals/import-lemonsqueezy-modal.tsx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants